#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
通信管理器重构性能测试
验证队列和独立线程机制的性能改进
"""

import sys
import time
import threading
import queue
import psutil
import os
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel, QTextEdit, QProgressBar
from PyQt6.QtCore import QTimer, pyqtSignal, QObject

# 添加src目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

try:
    from src.core.communication_manager_new import CommunicationManager
    print("✅ 成功导入重构后的通信管理器")
except ImportError as e:
    print(f"❌ 导入重构后的通信管理器失败: {e}")
    print("请确保已创建 communication_manager_new.py 文件")
    sys.exit(1)

class PerformanceTester(QObject):
    """性能测试器"""
    
    test_progress = pyqtSignal(int)
    test_result = pyqtSignal(str)
    status_updated = pyqtSignal(str)
    
    def __init__(self):
        super().__init__()
        self.comm_manager = None
        self.test_running = False
        self.test_thread = None
        self.test_results = {}
        
    def setup_test(self):
        """设置性能测试"""
        try:
            print("🔧 正在设置性能测试环境...")
            self.comm_manager = CommunicationManager()
            
            # 设置数据回调
            self.comm_manager.set_data_callback(self.on_data_processed)
            
            # 连接信号
            if self.comm_manager.data_processing_thread:
                self.comm_manager.data_processing_thread.data_processed.connect(self.on_data_processed)
                self.comm_manager.data_processing_thread.processing_error.connect(self.on_processing_error)
                self.comm_manager.data_processing_thread.processing_status.connect(self.on_processing_status)
                print("✅ 信号连接成功")
            
            self.status_updated.emit("性能测试环境设置完成")
            print("✅ 性能测试环境设置完成")
            return True
            
        except Exception as e:
            error_msg = f"设置性能测试环境失败: {e}"
            self.status_updated.emit(error_msg)
            print(f"❌ {error_msg}")
            return False
    
    def on_data_processed(self, data):
        """数据处理完成回调"""
        # 性能测试中，我们只关心处理速度，不需要详细的数据内容
        pass
    
    def on_processing_error(self, error_msg):
        """处理错误回调"""
        self.status_updated.emit(f"处理错误: {error_msg}")
        print(f"❌ 处理错误: {error_msg}")
    
    def on_processing_status(self, status_msg):
        """处理状态回调"""
        self.status_updated.emit(f"处理状态: {status_msg}")
        print(f"ℹ️ 处理状态: {status_msg}")
    
    def start_performance_test(self, test_type="burst"):
        """开始性能测试"""
        if not self.comm_manager:
            self.status_updated.emit("请先设置性能测试环境")
            print("❌ 请先设置性能测试环境")
            return
        
        print(f"🚀 开始{test_type}性能测试...")
        self.test_running = True
        self.test_thread = threading.Thread(target=self._run_performance_test, args=(test_type,))
        self.test_thread.daemon = True
        self.test_thread.start()
        self.status_updated.emit(f"{test_type}性能测试已开始")
    
    def stop_performance_test(self):
        """停止性能测试"""
        print("⏹️ 停止性能测试...")
        self.test_running = False
        if self.test_thread:
            self.test_thread.join(timeout=2.0)
        self.status_updated.emit("性能测试已停止")
    
    def _run_performance_test(self, test_type):
        """运行性能测试"""
        try:
            if test_type == "burst":
                self._burst_test()
            elif test_type == "continuous":
                self._continuous_test()
            elif test_type == "stress":
                self._stress_test()
            else:
                print(f"❌ 未知的测试类型: {test_type}")
                
        except Exception as e:
            error_msg = f"性能测试执行错误: {e}"
            self.status_updated.emit(error_msg)
            print(f"❌ {error_msg}")
    
    def _burst_test(self):
        """突发数据测试 - 短时间内发送大量数据"""
        print("📊 开始突发数据测试...")
        start_time = time.time()
        start_memory = psutil.Process().memory_info().rss / 1024 / 1024  # MB
        
        # 生成1000条数据，每条数据约1KB
        total_data = 1000
        for i in range(total_data):
            if not self.test_running:
                break
                
            # 生成测试数据
            test_data = self._generate_test_data(i, size="large")
            
            # 添加到处理队列
            self.comm_manager.add_data_to_queue(
                test_data,
                "突发测试",
                "custom_lis",
                f"BURST_{i}"
            )
            
            # 更新进度
            progress = int((i + 1) / total_data * 100)
            self.test_progress.emit(progress)
            
            # 短暂休眠，模拟真实情况
            time.sleep(0.001)  # 1ms间隔
        
        end_time = time.time()
        end_memory = psutil.Process().memory_info().rss / 1024 / 1024  # MB
        
        # 计算测试结果
        duration = end_time - start_time
        memory_used = end_memory - start_memory
        data_rate = total_data / duration if duration > 0 else 0
        
        # 等待队列处理完成
        self._wait_for_queue_processing()
        
        # 获取队列状态
        queue_status = self.comm_manager.get_queue_status()
        
        # 记录测试结果
        self.test_results['burst'] = {
            'total_data': total_data,
            'duration': duration,
            'data_rate': data_rate,
            'memory_used': memory_used,
            'queue_status': queue_status
        }
        
        # 发送测试结果
        result_msg = f"突发测试完成: 处理{total_data}条数据，耗时{duration:.2f}秒，速率{data_rate:.1f}条/秒，内存使用{memory_used:.1f}MB"
        self.test_result.emit(result_msg)
        print(f"✅ {result_msg}")
    
    def _continuous_test(self):
        """连续数据测试 - 长时间持续发送数据"""
        print("📊 开始连续数据测试...")
        start_time = time.time()
        start_memory = psutil.Process().memory_info().rss / 1024 / 1024  # MB
        
        # 持续发送数据30秒
        test_duration = 30
        count = 0
        
        while self.test_running and (time.time() - start_time) < test_duration:
            # 生成测试数据
            test_data = self._generate_test_data(count, size="medium")
            
            # 添加到处理队列
            self.comm_manager.add_data_to_queue(
                test_data,
                "连续测试",
                "custom_lis",
                f"CONT_{count}"
            )
            
            count += 1
            
            # 更新进度
            elapsed = time.time() - start_time
            progress = int((elapsed / test_duration) * 100)
            self.test_progress.emit(progress)
            
            # 控制发送速率
            time.sleep(0.01)  # 10ms间隔，100条/秒
        
        end_time = time.time()
        end_memory = psutil.Process().memory_info().rss / 1024 / 1024  # MB
        
        # 计算测试结果
        duration = end_time - start_time
        memory_used = end_memory - start_memory
        data_rate = count / duration if duration > 0 else 0
        
        # 等待队列处理完成
        self._wait_for_queue_processing()
        
        # 获取队列状态
        queue_status = self.comm_manager.get_queue_status()
        
        # 记录测试结果
        self.test_results['continuous'] = {
            'total_data': count,
            'duration': duration,
            'data_rate': data_rate,
            'memory_used': memory_used,
            'queue_status': queue_status
        }
        
        # 发送测试结果
        result_msg = f"连续测试完成: 处理{count}条数据，耗时{duration:.2f}秒，速率{data_rate:.1f}条/秒，内存使用{memory_used:.1f}MB"
        self.test_result.emit(result_msg)
        print(f"✅ {result_msg}")
    
    def _stress_test(self):
        """压力测试 - 高频率发送数据"""
        print("📊 开始压力测试...")
        start_time = time.time()
        start_memory = psutil.Process().memory_info().rss / 1024 / 1024  # MB
        
        # 高频率发送数据，测试系统极限
        test_duration = 10  # 10秒
        count = 0
        
        while self.test_running and (time.time() - start_time) < test_duration:
            # 生成测试数据
            test_data = self._generate_test_data(count, size="small")
            
            # 添加到处理队列
            self.comm_manager.add_data_to_queue(
                test_data,
                "压力测试",
                "custom_lis",
                f"STRESS_{count}"
            )
            
            count += 1
            
            # 更新进度
            elapsed = time.time() - start_time
            progress = int((elapsed / test_duration) * 100)
            self.test_progress.emit(progress)
            
            # 最小间隔，测试极限
            time.sleep(0.001)  # 1ms间隔，1000条/秒
        
        end_time = time.time()
        end_memory = psutil.Process().memory_info().rss / 1024 / 1024  # MB
        
        # 计算测试结果
        duration = end_time - start_time
        memory_used = end_memory - start_memory
        data_rate = count / duration if duration > 0 else 0
        
        # 等待队列处理完成
        self._wait_for_queue_processing()
        
        # 获取队列状态
        queue_status = self.comm_manager.get_queue_status()
        
        # 记录测试结果
        self.test_results['stress'] = {
            'total_data': count,
            'duration': duration,
            'data_rate': data_rate,
            'memory_used': memory_used,
            'queue_status': queue_status
        }
        
        # 发送测试结果
        result_msg = f"压力测试完成: 处理{count}条数据，耗时{duration:.2f}秒，速率{data_rate:.1f}条/秒，内存使用{memory_used:.1f}MB"
        self.test_result.emit(result_msg)
        print(f"✅ {result_msg}")
    
    def _wait_for_queue_processing(self):
        """等待队列处理完成"""
        print("⏳ 等待队列处理完成...")
        max_wait_time = 30  # 最多等待30秒
        start_wait = time.time()
        
        while self.test_running and (time.time() - start_wait) < max_wait_time:
            queue_status = self.comm_manager.get_queue_status()
            if queue_status.get('queue_size', 0) == 0:
                print("✅ 队列处理完成")
                break
            time.sleep(0.1)
        else:
            print("⚠️ 队列处理超时")
    
    def _generate_test_data(self, count, size="medium"):
        """生成测试数据"""
        if size == "small":
            # 小数据：约100字节
            data = f"<TRANSMIT>TEST_{count:04d}</TRANSMIT>"
        elif size == "medium":
            # 中等数据：约500字节
            data = f"""<TRANSMIT>
<M>TEST|{count:04d}</M>
<I>sample|2025-01-27|SAMPLE_{count:04d}</I>
<R>HbA1c|6.5|HbA0|87.0</R>
</TRANSMIT>"""
        else:  # large
            # 大数据：约1KB
            data = f"""<TRANSMIT>
<M>TEST_MACHINE|SN{count:04d}</M>
<I>sample|2025-01-27-14-30|SAMPLE_{count:04d}|SAMPLE_{count:04d}|RACK001|A01|血液样本</I>
<R>HbA1a|5.2|HbA1b|0.8|HbF|0.5|LA1c|0.3|HbA1c|6.8|HbA0|87.4|eAG|7.8</R>
<IMAGE>
<NAME>sample_{count:04d}.jpg</NAME>
<SIZE>1024</SIZE>
<DATA>FFD8FFE000104A46494600010101006000600000FFDB004300080606070605080707070909080A0C140D0C0B0B0C1912130F141D1A1F1E1D1A1C1C20242E2720222C231C1C2837292C30313434341F27393D38323C2E333432FFC0000B08001F000101011100FFC4001F0000010501010101010100000000000000000102030405060708090A0BFFC400B5100002010303020403050504040000017D01020300041105122131410613516107227114328191A1082342B1C11552D1F02433627282090A161718191A25262728292A3435363738393A434445464748494A535455565758595A636465666768696A737475767778797A838485868788898A92939495969798999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE1E2E3E4E5E6E7E8E9EAF1F2F3F4F5F6F7F8F9FAFFDA0008010100003F00</DATA>
</IMAGE>
</TRANSMIT>"""
        
        return data.encode('utf-8')
    
    def get_test_summary(self):
        """获取测试总结"""
        if not self.test_results:
            return "暂无测试结果"
        
        summary = "📊 性能测试总结:\n"
        for test_name, result in self.test_results.items():
            summary += f"\n{test_name.upper()}测试:\n"
            summary += f"  数据量: {result['total_data']} 条\n"
            summary += f"  耗时: {result['duration']:.2f} 秒\n"
            summary += f"  处理速率: {result['data_rate']:.1f} 条/秒\n"
            summary += f"  内存使用: {result['memory_used']:.1f} MB\n"
            summary += f"  队列状态: {result['queue_status']}\n"
        
        return summary
    
    def clear_test_results(self):
        """清空测试结果"""
        self.test_results.clear()
        self.status_updated.emit("测试结果已清空")
        print("🧹 测试结果已清空")

class PerformanceTestWindow(QWidget):
    """性能测试窗口"""
    
    def __init__(self):
        super().__init__()
        self.tester = PerformanceTester()
        self.init_ui()
        self.setup_connections()
        
        print("🎉 性能测试窗口已创建")
    
    def init_ui(self):
        """初始化界面"""
        self.setWindowTitle("通信管理器重构性能测试")
        self.setGeometry(100, 100, 1000, 800)
        
        # 布局
        layout = QVBoxLayout(self)
        
        # 标题
        title = QLabel("🚀 通信管理器重构性能测试")
        title.setStyleSheet("font-size: 18px; font-weight: bold; margin: 10px;")
        layout.addWidget(title)
        
        # 说明
        description = QLabel("本测试验证重构后的通信管理器在大量数据处理时的性能表现")
        description.setStyleSheet("margin: 5px; color: #666;")
        layout.addWidget(description)
        
        # 控制按钮
        self.setup_btn = QPushButton("🔧 设置测试环境")
        self.burst_btn = QPushButton("💥 突发测试")
        self.continuous_btn = QPushButton("🔄 连续测试")
        self.stress_btn = QPushButton("⚡ 压力测试")
        self.stop_btn = QPushButton("⏹️ 停止测试")
        self.summary_btn = QPushButton("📊 测试总结")
        self.clear_btn = QPushButton("🧹 清空结果")
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        
        # 状态标签
        self.status_label = QLabel("状态: 未初始化")
        self.status_label.setStyleSheet("font-weight: bold; color: #333; margin: 10px;")
        
        # 日志显示
        log_label = QLabel("📝 测试日志:")
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        self.log_text.setMaximumHeight(400)
        
        # 添加到布局
        layout.addWidget(self.setup_btn)
        layout.addWidget(self.burst_btn)
        layout.addWidget(self.continuous_btn)
        layout.addWidget(self.stress_btn)
        layout.addWidget(self.stop_btn)
        layout.addWidget(self.progress_bar)
        layout.addWidget(self.status_label)
        layout.addWidget(self.summary_btn)
        layout.addWidget(self.clear_btn)
        layout.addWidget(log_label)
        layout.addWidget(self.log_text)
        
        # 初始按钮状态
        self.burst_btn.setEnabled(False)
        self.continuous_btn.setEnabled(False)
        self.stress_btn.setEnabled(False)
        self.stop_btn.setEnabled(False)
        self.summary_btn.setEnabled(False)
        self.clear_btn.setEnabled(False)
        
        print("🎨 界面初始化完成")
    
    def setup_connections(self):
        """设置信号连接"""
        self.setup_btn.clicked.connect(self.setup_test)
        self.burst_btn.clicked.connect(lambda: self.start_test("burst"))
        self.continuous_btn.clicked.connect(lambda: self.start_test("continuous"))
        self.stress_btn.clicked.connect(lambda: self.start_test("stress"))
        self.stop_btn.clicked.connect(self.stop_test)
        self.summary_btn.clicked.connect(self.show_summary)
        self.clear_btn.clicked.connect(self.clear_results)
        
        # 连接测试器信号
        self.tester.test_progress.connect(self.update_progress)
        self.tester.test_result.connect(self.on_test_result)
        self.tester.status_updated.connect(self.on_status_updated)
        
        print("🔗 信号连接完成")
    
    def setup_test(self):
        """设置测试"""
        if self.tester.setup_test():
            self.setup_btn.setEnabled(False)
            self.burst_btn.setEnabled(True)
            self.continuous_btn.setEnabled(True)
            self.stress_btn.setEnabled(True)
            self.summary_btn.setEnabled(True)
            self.clear_btn.setEnabled(True)
            self.log_message("✅ 测试环境设置成功")
        else:
            self.log_message("❌ 测试环境设置失败")
    
    def start_test(self, test_type):
        """开始测试"""
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(0)
        self.burst_btn.setEnabled(False)
        self.continuous_btn.setEnabled(False)
        self.stress_btn.setEnabled(False)
        self.stop_btn.setEnabled(True)
        
        self.tester.start_performance_test(test_type)
        self.log_message(f"🚀 {test_type}测试已开始")
    
    def stop_test(self):
        """停止测试"""
        self.tester.stop_performance_test()
        self.progress_bar.setVisible(False)
        self.burst_btn.setEnabled(True)
        self.continuous_btn.setEnabled(True)
        self.stress_btn.setEnabled(True)
        self.stop_btn.setEnabled(False)
        self.log_message("⏹️ 测试已停止")
    
    def show_summary(self):
        """显示测试总结"""
        summary = self.tester.get_test_summary()
        self.log_message("📊 测试总结:")
        self.log_message(summary)
    
    def clear_results(self):
        """清空测试结果"""
        self.tester.clear_test_results()
        self.log_message("🧹 测试结果已清空")
    
    def update_progress(self, value):
        """更新进度条"""
        self.progress_bar.setValue(value)
    
    def on_test_result(self, result_msg):
        """测试结果回调"""
        self.log_message(result_msg)
        self.progress_bar.setVisible(False)
        self.burst_btn.setEnabled(True)
        self.continuous_btn.setEnabled(True)
        self.stress_btn.setEnabled(True)
        self.stop_btn.setEnabled(False)
    
    def on_status_updated(self, status_str):
        """状态更新回调"""
        self.status_label.setText(f"状态: {status_str}")
        self.log_message(status_str)
    
    def log_message(self, message):
        """记录日志消息"""
        timestamp = time.strftime("%H:%M:%S")
        self.log_text.append(f"[{timestamp}] {message}")
        
        # 限制日志行数
        lines = self.log_text.toPlainText().split('\n')
        if len(lines) > 1000:
            self.log_text.setPlainText('\n'.join(lines[-500:]))
    
    def closeEvent(self, event):
        """窗口关闭事件"""
        print("👋 正在关闭性能测试窗口...")
        self.tester.stop_performance_test()
        if self.tester.comm_manager:
            self.tester.comm_manager.stop_all()
            print("🛑 所有通信和数据处理已停止")
        event.accept()

def main():
    """主函数"""
    print("🚀 启动通信管理器重构性能测试...")
    
    app = QApplication(sys.argv)
    
    # 创建性能测试窗口
    window = PerformanceTestWindow()
    window.show()
    
    print("🎉 性能测试窗口已显示，开始测试...")
    
    # 运行应用
    sys.exit(app.exec())

if __name__ == "__main__":
    main()
